<template>
	<div class="zs-table-page-container">
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<div>
				<el-select v-model="searchObj.inspectionType" filterable clearable class="zs-select-md zs-space-right-sm" placeholder="类型" @change="queryList">
					<el-option v-for="item in inspectionTypeList" :key="item.id" :label="item.dicName" :value="item.id" />
				</el-select>
				<el-input v-model="searchObj.pointName" class="zs-select-md zs-space-right-sm" placeholder="点位名称" clearable />
				<el-input v-model="searchObj.routeName" class="zs-select-md zs-space-right-sm" placeholder="路线名称" clearable />
				<el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
					<template #reference>
						<el-button class="zs-btn-square-solid" :class="{ 'zs-btn-square-solid-active': searchObj.status || searchObj.角色名称 || searchObj.queryTime }">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</el-button>
					</template>
					<template #default>
						<el-select v-model="searchObj.status" clearable class="zs-select-md zs-space-right-sm" placeholder="状态" @change="queryList" :teleported="false">
							<el-option v-for="item in dictObj.WORK_ORDER_STATUS" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
						</el-select>
						<el-select v-model="searchObj.roleKey" filterable clearable class="zs-select-md zs-space-right-sm" placeholder="角色名称" @change="queryList" :teleported="false">
							<el-option v-for="item in roleList" :key="item.roleKey" :label="item.roleName" :value="item.roleKey" />
						</el-select>
						<el-date-picker v-model="searchObj.queryTime" class="zs-space-right-sm" :type="activeTab" placeholder="计划完成时间" value-format="YYYY-MM-DD" :teleported="false" :clearable="false" :disabled-date="disabledDate" />
					</template>
				</el-popover>
				<el-button class="zs-btn-plain" @click="queryList"> 查询 </el-button>
			</div>
			<div class="zs-layout-flex-row zs-layout-items-center">
				<el-button :class="activeTab == 'date' ? 'zs-btn-primary' : 'zs-btn-info'" @click="tabChange('date')">按日</el-button>
				<el-button class="zs-space-left-sm" :class="activeTab == 'month' ? 'zs-btn-primary' : 'zs-btn-info'" @click="tabChange('month')">按月</el-button>
			</div>
		</div>

		<!-- teble -->
		<div class="zs-card zs-table-page-content">
			<el-table class="zs-table-page-main" :data="tableData.data" v-loading="tableData.loading" stripe>
				<el-table-column type="index" label="序号" width="60" :align="'center'" :index="index => index + 1 + (tableData.currentPage - 1) * curPageSize" />
				<el-table-column prop="inspectionTypeName" label="类型" show-overflow-tooltip align="center" :formatter="defaultTableData" />
				<el-table-column prop="pointName" label="点位名称" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="routeName" label="路线名称" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column label="状态" show-overflow-tooltip align="center">
					<template #default="{ row }">
						<span :class="{ to_be_started: row.status == 1, to_be_normal: row.status == 2, to_be_delay: row.status == 5, to_be_schedule: row.status == 10, to_be_overdue: row.status == 11 }">{{ row.statusName || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="roleName" label="角色名称" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="actualProcessor" label="实际处理人" minWidth="120" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="planCreateTime" label="开始时间" show-overflow-tooltip min-width="120" align="center" :formatter="defaultTableData" />
				<el-table-column prop="planCompleteTime" label="计划完成时间" show-overflow-tooltip align="center" minWidth="120" :formatter="defaultTableData" />
				<el-table-column prop="completeTime" label="实际完成时间" show-overflow-tooltip align="center" minWidth="120" :formatter="defaultTableData" />
				<el-table-column prop="" label="现场照片" width="90" align="center">
					<template #default="{ row }">
						<el-button class="zs-link" :disabled="row.list && row.list.length > 0 ? false : true" link size="small" @click="fetchImage(row)">查看</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="zs-space-top-sm zs-table-page-pagination">
				<el-pagination v-model:currentPage="tableData.currentPage" v-model:page-size="curPageSize" :page-sizes="curPageSizes" :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="pageChange('size', $event)" @current-change="pageChange('page', $event)" />
			</div>
			<el-image-viewer v-if="viewerVisible" :url-list="previewList" :initial-index="0" @close="viewerVisible = false" />
		</div>
	</div>
</template>

<script setup>
	import { ref, reactive } from 'vue';
	import { parseTime, defaultTableData } from '@/utils/publicUtils';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';
	import detailApi from '@/api/Manage/Business/detailPages';
	import { getPropertyDictoryApi } from '@/api/dbPublic.js';

	const store = useStore();
	const curPageSizes = ref(store.state.uiPageSizes);
	const curPageSize = ref(store.state.uiPageSizeDefault);
	const routeQuery = useRoute().query;
	let dictObj = store.getters.getDictObj(['WORK_ORDER_STATUS']);

	//查询条件
	let searchObj = reactive({ pageNumber: 1, pageSize: curPageSize.value, projectCode: routeQuery.projectCode, queryTime: routeQuery.queryTime });

	// 列表 filed
	let tableData = reactive({
		currentPage: 1,
		total: 0,
		loading: false,
		data: [],
	});

	// 列表数据源
	const queryList = async () => {
		tableData.loading = true;
		searchObj.queryTimeFlag = activeTab.value == 'date' ? 1 : 2;
		if (activeTab.value == 'month') {
			let lastDay = getLastDayOfMonth(searchObj.queryTime);
			searchObj.queryTime = lastDay;
		}
		let res = await detailApi.inspectionRouteDetailPointListApi(searchObj);
		if (res.data.code !== 200) return;
		initData(res.data.data.list);
		tableData.data = res.data.data.list || [];
		tableData.total = res.data.data.total || 0;
		tableData.loading = false;
	};

	const initData = list => {
		list.forEach(item => {
			item.planCreateTime = item.planCreateTime ? parseTime(item.planCreateTime, '{y}-{m}-{d} {h}:{i}') : '-';
			item.planCompleteTime = item.planCompleteTime ? parseTime(item.planCompleteTime, '{y}-{m}-{d} {h}:{i}') : '-';
			item.completeTime = item.completeTime ? parseTime(item.completeTime, '{y}-{m}-{d} {h}:{i}') : '-';
		});
	};

	//校验时间
	const disabledDate = time => {
		return time.getTime() > new Date(routeQuery.queryTime).getTime();
	};

	//tab查询
	let activeTab = ref(routeQuery.tabType);
	const tabChange = type => {
		activeTab.value = type;
		if (type == 'date') {
			searchObj.queryTime = routeQuery.queryTime;
		}
		queryList();
	};

	//字典 类型
	const inspectionTypeList = ref([]);
	const getDictory = async () => {
		let res = await getPropertyDictoryApi({ sort: true, delFalg: 0 });
		if (res.data.code !== 200) return;
		inspectionTypeList.value = res.data.data.INSPECTION_TYPE.slice(0, 3);
	};

	//角色
	const roleList = ref([]);
	const getRoleList = async () => {
		let res = await detailApi.planRoleDropApi();
		if (res.data.code !== 200) return;
		roleList.value = res.data.data || [];
	};

	// 分页
	const pageChange = (type, size) => {
		if (type == 'size') {
			searchObj.pageSize = size;
		} else {
			searchObj.pageNumber = size;
		}
		queryList();
	};

	//取某月最后一天的日期
	const getLastDayOfMonth = date => {
		const currentDate = routeQuery.queryTime.split('-');
		const year = new Date(date).getFullYear();
		const month = new Date(date).getMonth();
		const lastDay = new Date(year, month + 1, 0);
		const formattedDate = `${lastDay.getFullYear()}-${String(lastDay.getMonth() + 1).padStart(2, '0')}-${String(lastDay.getDate()).padStart(2, '0')}`;
		return year == currentDate[0] && month == currentDate[1] - 1 ? routeQuery.queryTime : formattedDate;
	};

	//预览图片
	const previewList = ref([]);
	const viewerVisible = ref(false);
	const fetchImage = async row => {
		previewList.value = row.list.map(item => item.url);
		viewerVisible.value = true;
	};

	getDictory();
	getRoleList();
	queryList();
</script>

<style scoped lang="scss">
	:deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
		background: #477afd;
	}
	:deep(.el-image-viewer__img) {
		max-height: 85% !important;
	}
	.to_be_started {
		color: #8ea2ee;
	}
	.to_be_normal {
		color: #43c902;
	}
	.to_be_delay {
		color: #ed1a2c;
	}
	.to_be_schedule {
		color: #ccc;
	}
	.to_be_overdue {
		color: #f7b500;
	}
</style>
